from flask import Blueprint, request, jsonify
from service.impl.user_service_impl import UserServiceImpl

user_blueprint = Blueprint('user', __name__)
user_service = UserServiceImpl()


@user_blueprint.route('/users', methods=['GET'])
def get_users():
    users = user_service.get_all_users()
    return jsonify(users)


@user_blueprint.route('/users/<int:user_id>', methods=['GET'])
def get_user(user_id):
    user = user_service.get_user_by_id(user_id)
    if user:
        return jsonify(user)
    else:
        return jsonify({'error': 'User not found'}), 404


@user_blueprint.route('/users', methods=['POST'])
def create_user():
    data = request.get_json()
    user = user_service.create_user(data)
    return jsonify(user), 201


@user_blueprint.route('/users/<int:user_id>', methods=['PUT'])
def update_user(user_id):
    data = request.get_json()
    user = user_service.update_user(user_id, data)
    if user:
        return jsonify(user)
    else:
        return jsonify({'error': 'User not found'}), 404


@user_blueprint.route('/users/<int:user_id>', methods=['DELETE'])
def delete_user(user_id):
    success = user_service.delete_user(user_id)
    if success:
        return jsonify({'message': 'User deleted successfully'})
    else:
        return jsonify({'error': 'User not found'}), 404
